package com.example.laixiaolu

import com.example.laixiaolu.adapter.StudentAdapter
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.laixiaolu.model.Student
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken
import com.google.gson.Gson
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.lang.reflect.Type

class MainActivity : AppCompatActivity() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: StudentAdapter
    private val studentList = mutableListOf<Student>()

    private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val newStudent = result.data?.getParcelableExtra<Student>("student")
            newStudent?.let {
                studentList.add(it)
                adapter.notifyItemInserted(studentList.size - 1)
                saveStudents()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = StudentAdapter(studentList)
        recyclerView.adapter = adapter

        findViewById<Button>(R.id.addButton).setOnClickListener {
            val intent = Intent(this, AddStudentActivity::class.java)
            resultLauncher.launch(intent)
        }

        loadStudents()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun loadStudents() {
        val file = File(filesDir, "students.json")
        if (file.exists()) {
            val reader = FileReader(file)
            val gson = Gson()
            val listType: Type = object : TypeToken<List<Student>>() {}.type
            val loadedStudents = gson.fromJson<List<Student>>(reader, listType)
            studentList.addAll(loadedStudents)
            adapter.notifyDataSetChanged()
            reader.close()
        }
    }

    private fun saveStudents() {
        val file = File(filesDir, "students.json")
        val writer = FileWriter(file)
        val gson = Gson()
        val json = gson.toJson(studentList)
        writer.write(json)
        writer.flush()
        writer.close()
    }
}